<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>FinData - 自选股票</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Arial', sans-serif;
            background-color: #0a0a0a;
            color: #e0e0e0;
        }
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px 30px;
            background-color: #121212;
            border-bottom: 1px solid #333;
        }
        .logo-container {
            display: flex;
            align-items: center;
        }
        .logo {
            width: 40px;
            height: 40px;
            margin-right: 10px;
            filter: drop-shadow(0 0 5px rgba(138, 43, 226, 0.7));
            animation: pulse 2s infinite alternate;
        }
        .logo-text {
            font-size: 24px;
            font-weight: bold;
            background: linear-gradient(90deg, #8a2be2, #a855f7, #c084fc);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            text-shadow: 0 0 10px rgba(168, 85, 247, 0.5);
            animation: shine 3s linear infinite;
            margin-right: auto;
        }
        .back-btn {
            padding: 10px 20px;
            background: linear-gradient(145deg, #4a4a4a, #2e2e2e);
            border-radius: 8px;
            color: white;
            font-weight: 500;
            cursor: pointer;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            margin-right: 20px;
        }
        .back-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(255, 255, 255, 0.1);
        }
        .page-title {
            font-size: 20px;
            font-weight: bold;
            color: #e0e0e0;
            flex-grow: 1;
            text-align: center;
        }
        .favorites-container {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 20px;
            padding: 30px;
            max-width: 1600px;
            margin: 0 auto;
        }
        @media (max-width: 1600px) {
            .favorites-container {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        @media (max-width: 1200px) {
            .favorites-container {
                grid-template-columns: repeat(3, 1fr);
            }
        }
        @media (max-width: 900px) {
            .favorites-container {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        @media (max-width: 600px) {
            .favorites-container {
                grid-template-columns: repeat(1, 1fr);
            }
        }
        .stock-card {
            display: flex;
            flex-direction: column;
            background-color: #1e1e1e;
            border-radius: 12px;
            padding: 15px;
            margin: 10px;
            width: 280px;
            height: 180px;
            position: relative;
            transition: all 0.3s;
            border: 1px solid #333;
        }
        .stock-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
            border-color: #8a2be2;
        }
        .stock-name {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .market-status {
            font-size: 12px;
            padding: 2px 8px;
            border-radius: 4px;
            font-weight: normal;
        }
        .status-open {
            background-color: rgba(0, 255, 0, 0.2);
            color: #4CAF50;
            border: 1px solid rgba(0, 255, 0, 0.3);
        }
        .status-closed {
            background-color: rgba(255, 152, 0, 0.2);
            color: #ff9800;
            border: 1px solid rgba(255, 152, 0, 0.3);
        }
        .status-non-trading {
            background-color: rgba(128, 128, 128, 0.2);
            color: #9e9e9e;
            border: 1px solid rgba(128, 128, 128, 0.3);
        }
        .stock-code {
            font-size: 14px;
            color: #888;
            margin-bottom: 15px;
        }
        .stock-price {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 10px;
        }
        .price-up {
            color: #f44336;
        }
        .price-down {
            color: #4CAF50;
        }
        .stock-change {
            display: flex;
            margin-bottom: 10px;
        }
        .stock-change-value {
            font-size: 16px;
            margin-right: 10px;
        }
        .stock-change-percent {
            font-size: 16px;
        }
        .stock-time {
            font-size: 12px;
            color: #888;
            margin-top: auto;
        }
        .remove-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.1);
            color: #888;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
        }
        .remove-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
            color: #fff;
        }
        .empty-message {
            text-align: center;
            color: #888;
            padding: 50px 0;
            font-size: 16px;
            display: none;
        }
        .controls {
            display: flex;
            justify-content: center;
            margin: 20px 0;
            gap: 20px;
        }
        .refresh-btn, .add-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 10px 20px;
            border-radius: 8px;
            background-color: #8a2be2;
            color: white;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }
        .refresh-btn svg, .add-btn svg {
            margin-right: 8px;
        }
        .refresh-btn:hover, .add-btn:hover {
            background-color: #9b4ddb;
            transform: translateY(-2px);
        }
        .refresh-btn.disabled {
            background-color: #555;
            cursor: not-allowed;
            opacity: 0.7;
        }
        .refresh-btn.disabled:hover {
            transform: none;
        }
        .update-status {
            text-align: center;
            color: #888;
            font-size: 14px;
            margin-top: 20px;
        }
        .market-closed-alert {
            text-align: center;
            color: #ff9800;
            font-size: 14px;
            margin: 10px 0;
            padding: 5px;
            background-color: rgba(255, 152, 0, 0.1);
            border-radius: 4px;
            display: none;
        }
        .login-warning {
            background-color: rgba(255, 152, 0, 0.2);
            color: #ff9800;
            padding: 10px 20px;
            border-radius: 8px;
            text-align: center;
            margin: 10px 30px;
            border: 1px solid rgba(255, 152, 0, 0.3);
            font-weight: 500;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background-color: #1e1e1e;
            border-radius: 12px;
            padding: 30px;
            width: 400px;
            max-width: 90%;
            box-shadow: 0 6px 24px rgba(0, 0, 0, 0.6);
        }
        .modal-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #e0e0e0;
        }
        .modal-input {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            background-color: #2a2a2a;
            border: 1px solid #444;
            border-radius: 6px;
            color: #e0e0e0;
            font-size: 16px;
            box-sizing: border-box;
        }
        .modal-input:focus {
            outline: none;
            border-color: #8a2be2;
        }
        .modal-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }
        .modal-btn {
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }
        .cancel-btn {
            background-color: #444;
            color: #e0e0e0;
        }
        .confirm-btn {
            background-color: #8a2be2;
            color: white;
        }
        .modal-btn:hover {
            transform: translateY(-2px);
        }
        
        /* 添加动画关键帧 */
        @keyframes pulse {
            0% {
                transform: scale(1);
                opacity: 0.8;
            }
            100% {
                transform: scale(1.1);
                opacity: 1;
                filter: drop-shadow(0 0 10px rgba(138, 43, 226, 0.9));
            }
        }
        
        @keyframes shine {
            to {
                background-position: 200% center;
            }
        }
        
        .debug-info pre {
            white-space: pre-wrap;
            font-family: monospace;
            color: #e0e0e0;
        }
        
        /* 版权信息样式 */
        .copyright-container {
            background-color: rgba(18, 18, 18, 0.8);
            padding: 15px;
            margin-top: 30px;
            text-align: center;
            border-top: 1px solid #333;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            z-index: 100;
        }
        
        .copyright {
            font-size: 12px;
            color: #666;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="back-btn" id="backBtn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M3 9L12 2L21 9V20C21 20.5304 20.7893 21.0391 20.4142 21.4142C20.0391 21.7893 19.5304 22 19 22H5C4.46957 22 3.96086 21.7893 3.58579 21.4142C3.21071 21.0391 3 20.5304 3 20V9Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M9 22V12H15V22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            返回主页
        </div>
        <div class="page-title">我的自选</div>
        <div class="logo-container">
            <svg class="logo" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
                <path d="M20 0 L40 20 L20 40 L0 20 Z" fill="#8a2be2"/>
                <path d="M10 10 L30 10 L30 30 L10 30 Z" fill="#00bfff"/>
                <path d="M15 15 L25 15 L25 25 L15 25 Z" fill="#4CAF50"/>
            </svg>
            <div class="logo-text">FinData</div>
        </div>
    </div>

    <div id="loginWarning" class="login-warning" style="display: none;">
        您当前未登录，自选数据仅保存在本地，登录后可永久保存
    </div>

    <div id="emptyMessage" class="empty-message">
        您还没有添加任何自选股票，点击下方"添加自选"按钮开始添加
    </div>

    <div id="favoritesContainer" class="favorites-container">
        <!-- 股票卡片将通过JavaScript动态添加 -->
    </div>

    <div class="update-status" id="updateStatus">上次更新: --</div>

    <div class="controls">
        <div class="refresh-btn" id="refreshBtn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4C7.58 4 4.01 7.58 4.01 12C4.01 16.42 7.58 20 12 20C15.73 20 18.84 17.45 19.73 14H17.65C16.83 16.33 14.61 18 12 18C8.69 18 6 15.31 6 12C6 8.69 8.69 6 12 6C13.66 6 15.14 6.69 16.22 7.78L13 11H20V4L17.65 6.35Z" fill="currentColor"/>
            </svg>
            刷新数据
        </div>
        <div class="add-btn" id="addBtn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 5V19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M5 12H19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            添加自选
        </div>
    </div>

    <!-- 添加自选股票的模态框 -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <div class="modal-title">添加自选股票</div>
            <input type="text" id="stockCodeInput" class="modal-input" placeholder="请输入股票代码（如：600000）">
            <div class="modal-buttons">
                <div class="modal-btn cancel-btn" id="cancelBtn">取消</div>
                <div class="modal-btn confirm-btn" id="confirmBtn">添加</div>
            </div>
        </div>
    </div>

    <!-- 未登录返回确认模态框 -->
    <div id="confirmBackModal" class="modal">
        <div class="modal-content">
            <div class="modal-title" style="color: #ff9800;">未登录提醒</div>
            <p style="color: #e0e0e0; margin-bottom: 10px; font-size: 16px;">您当前处于<span style="color: #ff9800; font-weight: bold;">未登录</span>状态！</p>
            <p style="color: #e0e0e0; margin-bottom: 20px;">直接返回主界面会导致自选结果清空。建议先登录以保存您的自选数据。</p>
            <div class="modal-buttons" style="justify-content: space-between;">
                <div class="modal-btn" id="loginBtn" style="background: linear-gradient(145deg, #8a2be2, #4b0082); color: white; flex: 1; margin-right: 10px;">登录</div>
                <div class="modal-btn confirm-btn" id="confirmBackBtn" style="flex: 1;">仍然返回</div>
            </div>
        </div>
    </div>

    <div class="market-closed-alert" id="marketClosedAlert"></div>
    <div class="data-source" style="text-align: center; margin-top: 20px; color: #888; font-size: 12px;">数据来源: 腾讯财经</div>

    <!-- 添加底部间距，防止内容被固定的版权信息遮挡 -->
    <div style="height: 60px;"></div>

    <!-- 页面底部的版权信息已经通过copyright-container添加，不需要这个footer -->
    
    <!-- 添加隐藏的调试信息 -->
    <div id="debugInfo" style="position: fixed; top: 10px; right: 10px; background: rgba(0,0,0,0.7); padding: 10px; border-radius: 5px; z-index: 9999; display: none; color: white;">
        <h3>调试信息</h3>
        <pre id="debugOutput">等待加载...</pre>
        <div>
            <button onclick="directLoginTest()">直接登录测试</button>
            <button onclick="document.getElementById('debugInfo').style.display='none'">关闭</button>
        </div>
    </div>

    <script>
        // 在顶部添加全局错误处理
        window.onerror = function(message, source, lineno, colno, error) {
            console.error('全局错误:', message);
            console.error('错误来源:', source);
            console.error('行号:', lineno);
            console.error('列号:', colno);
            console.error('错误对象:', error);
            
            // 显示错误信息
            const errorDiv = document.createElement('div');
            errorDiv.style.position = 'fixed';
            errorDiv.style.bottom = '20px';
            errorDiv.style.right = '20px';
            errorDiv.style.backgroundColor = 'rgba(255, 0, 0, 0.8)';
            errorDiv.style.color = 'white';
            errorDiv.style.padding = '10px';
            errorDiv.style.borderRadius = '5px';
            errorDiv.style.zIndex = '9999';
            errorDiv.style.maxWidth = '300px';
            errorDiv.style.wordBreak = 'break-word';
            errorDiv.innerHTML = `<strong>JavaScript错误:</strong><br>${message}`;
            
            document.body.appendChild(errorDiv);
            
            // 5秒后自动消失
            setTimeout(() => {
                if (document.body.contains(errorDiv)) {
                    document.body.removeChild(errorDiv);
                }
            }, 5000);
            
            return true; // 阻止默认错误处理
        };

        // 页面加载完成时
        window.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成，DOM已准备好');
        });

        // 在页面完全加载后
        window.addEventListener('load', function() {
            console.log('页面完全加载完成，包括所有资源');
        });

        // 用户登录状态
        let isLoggedIn = false;
        // 本地存储的自选股票
        let localFavorites = [];
        // 交易日历数据
        const tradingDays = [];
        
        // 页面加载时执行
        document.addEventListener('DOMContentLoaded', async function() {
            console.log('页面加载完成，开始初始化');
            
            // 加载本地存储的自选股票
            loadLocalFavorites();
            
            // 加载交易日历
            await loadTradingCalendar();
            
            // 加载自选股票并检查登录状态
            await loadFavorites();
            console.log('初始化完成，登录状态:', isLoggedIn);
            
            // 设置自动更新定时器（每分钟更新一次）
            setInterval(refreshStockData, 60000);
        });
        
        // 加载本地存储的自选股票
        function loadLocalFavorites() {
            const storedFavorites = localStorage.getItem('favorites');
            if (storedFavorites) {
                try {
                    localFavorites = JSON.parse(storedFavorites);
                } catch (e) {
                    console.error('解析本地自选股票失败:', e);
                    localFavorites = [];
                }
            }
        }
        
        // 保存自选股票到本地存储
        function saveLocalFavorites() {
            localStorage.setItem('favorites', JSON.stringify(localFavorites));
        }
        
        // 加载交易日历
        async function loadTradingCalendar() {
            try {
                // 使用API端点获取交易日历数据
                const response = await fetch('/api/trading-calendar');
                if (response.ok) {
                    const data = await response.json();
                    if (data.tradingDays && Array.isArray(data.tradingDays)) {
                        // 清空原有数据
                        tradingDays.length = 0;
                        // 添加新数据
                        data.tradingDays.forEach(date => {
                            if (date) {
                                tradingDays.push(date);
                            }
                        });
                        console.log(`交易日历加载成功，共${tradingDays.length}个交易日`);
                    }
                } else {
                    console.error('获取交易日历失败');
                }
            } catch (error) {
                console.error('加载交易日历错误:', error);
            }
        }
        
        // 检查是否为交易日
        function checkTradingDay() {
            const now = new Date();
            const day = now.getDay();
            
            // 周末不是交易日
            if (day === 0 || day === 6) {
                return false;
            }
            
            // 格式化当前日期为YYYY-MM-DD格式，用于与交易日历比对
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const date = String(now.getDate()).padStart(2, '0');
            const today = `${year}-${month}-${date}`;
            
            // 如果交易日历已加载，则检查当前日期是否在交易日历中
            if (tradingDays.length > 0) {
                return tradingDays.includes(today);
            }
            
            // 如果交易日历未加载，则仅根据周末判断
            return true;
        }
        
        // 检查登录状态
        async function checkLoginStatus() {
            try {
                const response = await fetch('/api/favorites');
                if (response.ok) {
                    const data = await response.json();
                    isLoggedIn = data.isLoggedIn;
                    console.log('检查登录状态结果:', isLoggedIn);
                }
            } catch (error) {
                console.error('检查登录状态错误:', error);
            }
        }
        
        // 确认返回按钮点击事件
        document.getElementById('confirmBackBtn').addEventListener('click', function() {
            // 用户选择仍然返回，直接跳转到主页
            window.location.href = '/blank';
        });
        
        // 登录按钮点击事件
        document.getElementById('loginBtn').addEventListener('click', function() {
            try {
                console.log('登录按钮被点击');
                
                // 检查按钮是否可点击
                if (this.getAttribute('disabled')) {
                    console.log('登录按钮被禁用');
                    return;
                }
                
                // 临时禁用按钮防止重复点击
                this.setAttribute('disabled', 'true');
                this.style.opacity = '0.7';
                this.textContent = '正在跳转...';
                
                // 将当前页面URL存储在会话存储中，以便登录后返回
                console.log('保存返回URL到会话存储');
                sessionStorage.setItem('returnUrl', '/favorites');
                
                // 保持自选数据，跳转到登录页
                console.log('跳转到登录页面');
                setTimeout(() => {
                    window.location.href = '/login';
                }, 100);
            } catch (error) {
                console.error('登录按钮点击事件发生错误:', error);
                alert('跳转登录页面失败: ' + error.message);
                
                // 恢复按钮状态
                this.removeAttribute('disabled');
                this.style.opacity = '1';
                this.textContent = '我要登录';
            }
        });
        
        // 刷新按钮点击事件
        document.getElementById('refreshBtn').addEventListener('click', refreshStockData);
        
        // 添加按钮点击事件
        document.getElementById('addBtn').addEventListener('click', function() {
            document.getElementById('addModal').style.display = 'flex';
        });
        
        // 取消按钮点击事件
        document.getElementById('cancelBtn').addEventListener('click', function() {
            document.getElementById('addModal').style.display = 'none';
            document.getElementById('stockCodeInput').value = '';
        });
        
        // 确认添加按钮点击事件
        document.getElementById('confirmBtn').addEventListener('click', async function() {
            const stockCode = document.getElementById('stockCodeInput').value.trim();
            if (!stockCode) {
                alert('请输入股票代码');
                return;
            }
            
            // 验证股票代码格式
            if (!/^\d{6}$/.test(stockCode)) {
                alert('请输入正确的股票代码格式（6位数字）');
                return;
            }
            
            try {
                // 先查询股票信息
                // 确定股票市场
                let market;
                if (stockCode.startsWith('60') || stockCode.startsWith('68')) {
                    market = 'sh'; // 上海证券交易所
                } else if (stockCode.startsWith('00') || stockCode.startsWith('30')) {
                    market = 'sz'; // 深圳证券交易所
                } else {
                    market = 'bj'; // 北京证券交易所
                }
                
                const fullCode = `s_${market}${stockCode}`;
                
                // 添加时间戳防止缓存
                const timestamp = new Date().getTime();
                const url = `https://qt.gtimg.cn/?q=${fullCode}&_=${timestamp}`;
                
                // 使用代理服务器避免跨域问题
                const proxyUrl = `/api/stock-proxy?url=${encodeURIComponent(url)}`;
                
                const infoResponse = await fetch(proxyUrl);
                
                if (!infoResponse.ok) {
                    alert('获取股票信息失败，请确认股票代码是否正确');
                    return;
                }
                
                // 获取股票名称和信息
                const content = await infoResponse.text();
                console.log('获取到的股票信息:', content);
                
                // 腾讯API格式: v_s_sh000001="1~上证指数~000001~3399.77~14.41~0.43~427347947~51187994~~650012.70~ZS";
                const regex = new RegExp(`v_${fullCode}="([^"]+)"`);
                const match = content.match(regex);
                
                console.log(`股票${fullCode}匹配:`, match ? '成功' : '失败');
                
                let stockInfo = null;
                
                if (match && match[1]) {
                    const stockData = match[1].split('~');
                    console.log('股票数据:', stockData);
                    
                    // 腾讯API简化格式数据索引：1是股票名称
                    // 检查股票名称是否为乱码
                    let stockName = stockData[1];
                    const hasBadChar = /[\ufffd\?]/.test(stockName); // 检测和?字符
                    
                    if (!stockName || hasBadChar) {
                        console.warn('股票名称可能存在编码问题:', stockName);
                        // 尝试使用股票代码作为名称
                        stockName = `股票${stockCode}`;
                    }
                    
                    stockInfo = {
                        code: stockCode,
                        name: ensureValidStockName(stockName)
                    };
                } else {
                    alert('未找到该股票信息，请确认股票代码是否正确');
                    return;
                }
                
                console.log('解析后的股票信息:', stockInfo);
                
                if (isLoggedIn) {
                    // 已登录，添加到服务器
                    const response = await fetch('/api/add-favorite', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ 
                            stockCode: stockInfo.code,
                            stockName: stockInfo.name
                        }),
                        credentials: 'include'
                    });
                    
                    if (response.ok) {
                        // 关闭模态框
                        document.getElementById('addModal').style.display = 'none';
                        document.getElementById('stockCodeInput').value = '';
                        
                        // 重新加载自选股票
                        loadFavorites();
                    } else {
                        const errorData = await response.json();
                        alert(errorData.message || '添加自选失败，请重试');
                    }
                } else {
                    // 未登录，添加到本地存储
                    // 检查是否已存在
                    if (localFavorites.some(item => item.code === stockInfo.code)) {
                        alert('该股票已在自选列表中');
                        return;
                    }
                    
                    // 添加到本地存储
                    localFavorites.push({
                        code: stockInfo.code,
                        name: stockInfo.name
                    });
                    
                    // 保存到本地存储
                    saveLocalFavorites();
                    
                    // 关闭模态框
                    document.getElementById('addModal').style.display = 'none';
                    document.getElementById('stockCodeInput').value = '';
                    
                    // 渲染自选股票
                    renderFavorites(localFavorites);
                    
                    // 刷新数据
                    refreshStockData();
                }
            } catch (error) {
                console.error('添加自选请求错误:', error);
                alert('网络请求失败，请检查您的网络连接');
            }
        });
        
        // 加载自选股票
        async function loadFavorites() {
            try {
                const response = await fetch('/api/favorites');
                if (response.ok) {
                    const data = await response.json();
                    
                    // 设置登录状态
                    isLoggedIn = data.isLoggedIn;
                    
                    // 显示或隐藏登录提示
                    const loginWarning = document.getElementById('loginWarning');
                    
                    if (!isLoggedIn) {
                        // 未登录，显示提示并使用本地存储
                        loginWarning.style.display = 'block';
                        
                        // 显示本地存储的自选股票
                        renderFavorites(localFavorites);
                        
                        // 如果有自选股票，刷新数据
                        if (localFavorites.length > 0) {
                            refreshStockData();
                        }
                    } else {
                        // 已登录，隐藏提示
                        loginWarning.style.display = 'none';
                        
                        // 检查本地是否有自选股票需要导入
                        if (localFavorites.length > 0) {
                            await importLocalFavorites();
                            // 导入后清空本地存储
                            localFavorites = [];
                            saveLocalFavorites();
                        }
                        
                        // 显示或隐藏空消息
                        const emptyMessage = document.getElementById('emptyMessage');
                        if (data.favorites.length === 0) {
                            emptyMessage.style.display = 'block';
                        } else {
                            emptyMessage.style.display = 'none';
                        }
                        
                        // 渲染自选股票
                        renderFavorites(data.favorites);
                        
                        // 如果有自选股票，刷新数据
                        if (data.favorites.length > 0) {
                            refreshStockData();
                        }
                    }
                } else {
                    console.error('获取自选股票失败');
                }
            } catch (error) {
                console.error('获取自选股票错误:', error);
            }
        }
        
        // 导入本地自选股票到服务器
        async function importLocalFavorites() {
            try {
                console.log('开始导入本地自选股票，数量:', localFavorites.length);
                
                // 依次添加每个本地自选股票
                for (const stock of localFavorites) {
                    try {
                        const response = await fetch('/api/add-favorite', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ 
                                stockCode: stock.code,
                                stockName: stock.name
                            }),
                            credentials: 'include'
                        });
                        
                        if (!response.ok) {
                            console.error('导入自选股票失败:', stock.code);
                        }
                    } catch (err) {
                        console.error('导入单个自选股票出错:', err);
                    }
                }
                
                console.log('本地自选股票导入完成');
                return true;
            } catch (error) {
                console.error('导入本地自选股票错误:', error);
                return false;
            }
        }
        
        // 渲染自选股票
        function renderFavorites(favorites) {
            const container = document.getElementById('favoritesContainer');
            container.innerHTML = '';
            
            // 显示或隐藏空消息
            const emptyMessage = document.getElementById('emptyMessage');
            if (favorites.length === 0) {
                emptyMessage.style.display = 'block';
                return;
            } else {
                emptyMessage.style.display = 'none';
            }
            
            favorites.forEach(stock => {
                const card = document.createElement('div');
                card.className = 'stock-card';
                card.id = `stock-${stock.code || stock.Code}`;
                
                // 确定股票市场
                const stockCode = stock.code || stock.Code;
                let market;
                if (stockCode.startsWith('60') || stockCode.startsWith('68')) {
                    market = 'sh'; // 上海证券交易所
                } else if (stockCode.startsWith('00') || stockCode.startsWith('30')) {
                    market = 'sz'; // 深圳证券交易所
                } else {
                    market = 'bj'; // 北京证券交易所
                }
                const fullCode = `${market}${stockCode}`;
                
                // 确保股票名称正确显示
                const stockName = ensureValidStockName(stock.name || stock.Name);
                
                card.innerHTML = `
                    <div class="stock-name">
                        ${stockName}
                        <div class="market-status status-closed">已收盘</div>
                    </div>
                    <div class="stock-code">${stockCode}</div>
                    <div class="stock-price">--</div>
                    <div class="stock-change">
                        <span class="stock-change-value">--</span>
                        <span class="stock-change-percent">--</span>
                    </div>
                    <div class="stock-time">更新时间: --</div>
                    <div class="remove-btn" data-code="${stockCode}">×</div>
                `;
                
                // 添加点击事件，跳转到详情页
                card.addEventListener('click', function(e) {
                    // 如果点击的是删除按钮，不跳转
                    if (e.target.classList.contains('remove-btn')) {
                        return;
                    }
                    // 判断股票市场
                    const code = stockCode;
                    let market;
                    if (code.startsWith('60') || code.startsWith('68')) {
                        market = 'sh'; // 上海证券交易所
                    } else if (code.startsWith('00') || code.startsWith('30')) {
                        market = 'sz'; // 深圳证券交易所
                    } else {
                        market = 'bj'; // 北京证券交易所
                    }
                    const fullCode = `${market}${code}`;
                    // 跳转到腾讯财经股票详情页
                    window.open(`https://gu.qq.com/${fullCode}/zs`, '_blank');
                });
                
                container.appendChild(card);
            });
            
            // 添加删除按钮点击事件
            document.querySelectorAll('.remove-btn').forEach(btn => {
                btn.addEventListener('click', async function(e) {
                    e.stopPropagation();
                    const stockCode = this.getAttribute('data-code');
                    
                    // 显示自定义确认对话框
                    showDeleteConfirmDialog(stockCode, stockName);
                });
            });
        }
        
        // 确保股票名称正确显示
        function ensureValidStockName(name) {
            // 检查是否为纯数字
            if (/^\d+$/.test(name)) {
                return '加载中...'; // 如果是纯数字，显示加载中
            }
            // 检查是否包含股票名称
            if (name && name.length > 0 && name !== 'undefined') {
                return name;
            }
            return '加载中...';
        }
        
        // 刷新股票数据
        async function refreshStockData() {
            try {
                // 获取所有自选股票
                let favorites;
                
                if (isLoggedIn) {
                    // 已登录，从服务器获取
                    const response = await fetch('/api/favorites');
                    if (!response.ok) {
                        console.error('获取自选股票失败');
                        return;
                    }
                    
                    const data = await response.json();
                    favorites = data.favorites;
                } else {
                    // 未登录，使用本地存储
                    favorites = localFavorites;
                }
                
                if (favorites.length === 0) {
                    return;
                }
                
                // 检查是否为交易时间
                const now = new Date();
                const hour = now.getHours();
                const minute = now.getMinutes();
                const isMarketOpen = (hour === 9 && minute >= 30) || (hour > 9 && hour < 11) || 
                                   (hour === 11 && minute <= 30) || 
                                   (hour >= 13 && hour < 15);
                
                const isTrading = checkTradingDay();
                const refreshBtn = document.getElementById('refreshBtn');
                const marketClosedAlert = document.getElementById('marketClosedAlert');
                
                if (!isTrading) {
                    // 非交易日
                    marketClosedAlert.style.display = 'block';
                    marketClosedAlert.textContent = '今日为非交易日，数据无法刷新';
                    refreshBtn.classList.add('disabled');
                } else if (!isMarketOpen) {
                    // 交易日但不在交易时间
                    marketClosedAlert.style.display = 'block';
                    marketClosedAlert.textContent = '当前为非交易时段，数据为收盘数据';
                    refreshBtn.classList.add('disabled');
                } else {
                    // 交易时间
                    marketClosedAlert.style.display = 'none';
                    refreshBtn.classList.remove('disabled');
                }
                
                // 构建查询字符串
                const codes = favorites.map(stock => {
                    const stockCode = stock.code || stock.Code;
                    let market;
                    if (stockCode.startsWith('60') || stockCode.startsWith('68')) {
                        market = 'sh'; // 上海证券交易所
                    } else if (stockCode.startsWith('00') || stockCode.startsWith('30')) {
                        market = 'sz'; // 深圳证券交易所
                    } else {
                        market = 'bj'; // 北京证券交易所
                    }
                    // 腾讯API使用s_前缀表示简化版数据
                    return `s_${market}${stockCode}`;
                }).join(',');
                
                console.log('请求的股票代码:', codes);
                
                // 添加时间戳防止缓存
                const timestamp = new Date().getTime();
                const url = `https://qt.gtimg.cn/?q=${codes}&_=${timestamp}`;
                
                // 使用代理服务器避免跨域问题
                const proxyUrl = `/api/stock-proxy?url=${encodeURIComponent(url)}`;
                console.log('代理请求URL:', proxyUrl);
                
                const dataResponse = await fetch(proxyUrl);
                
                if (dataResponse.ok) {
                    const data = await dataResponse.text();
                    console.log('API返回数据前200个字符:', data.substring(0, 200));
                    processTencentStockData(data, favorites, isTrading, isMarketOpen);
                    
                    // 更新刷新时间
                    const now = new Date();
                    document.getElementById('updateStatus').textContent = `上次更新: ${now.toLocaleTimeString()}`;
                } else {
                    console.error('获取股票数据失败');
                }
            } catch (error) {
                console.error('刷新股票数据错误:', error);
            }
        }
        
        // 处理腾讯股票数据
        function processTencentStockData(data, favorites, isTrading, isMarketOpen) {
            console.log('处理股票数据，原始数据长度:', data.length);
            console.log('交易日状态:', isTrading ? '是交易日' : '非交易日');
            console.log('交易时间状态:', isMarketOpen ? '交易时段' : '非交易时段');
            
            // 解析数据
            favorites.forEach(stock => {
                const stockCode = stock.code || stock.Code;
                let market;
                if (stockCode.startsWith('60') || stockCode.startsWith('68')) {
                    market = 'sh'; // 上海证券交易所
                } else if (stockCode.startsWith('00') || stockCode.startsWith('30')) {
                    market = 'sz'; // 深圳证券交易所
                } else {
                    market = 'bj'; // 北京证券交易所
                }
                const fullCode = `s_${market}${stockCode}`;
                
                // 腾讯API格式: v_s_sh000001="1~上证指数~000001~3399.77~14.41~0.43~427347947~51187994~~650012.70~ZS";
                const regex = new RegExp(`v_${fullCode}="([^"]+)"`);
                const match = data.match(regex);
                
                console.log(`查找股票 ${fullCode} 数据:`, match ? '找到' : '未找到');
                
                if (match && match[1]) {
                    const stockData = match[1].split('~');
                    console.log(`股票 ${fullCode} 数据:`, stockData);
                    
                    // 输出所有数据项，帮助调试
                    if (stockData.length > 0) {
                        console.log(`股票 ${fullCode} 数据项:`);
                        stockData.forEach((item, index) => {
                            console.log(`  [${index}]: ${item}`);
                        });
                    }
                    
                    updateTencentStockCard(stockCode, stockData, isTrading, isMarketOpen);
                } else {
                    console.error(`未找到股票 ${fullCode} 的数据`);
                }
            });
        }
        
        // 更新股票卡片（腾讯数据格式）
        function updateTencentStockCard(stockCode, data, isTrading, isMarketOpen) {
            const card = document.getElementById(`stock-${stockCode}`);
            if (card) {
                // 打印调试信息
                console.log(`更新股票卡片: ${stockCode}`, data);
                
                // 腾讯API简化格式数据索引：
                // 0: 未知，1: 股票名称，2: 股票代码，3: 当前价格，4: 涨跌额
                // 5: 涨跌幅，6: 成交量，7: 成交额
                const stockName = ensureValidStockName(data[1]);
                const currentPrice = data[3] || '--';
                const changeValue = data[4] || '--';
                const changePercent = data[5] || '--'; // 已经带有%符号
                
                // 更新时间
                const now = new Date();
                const updateTime = now.toLocaleTimeString();
                
                // 调试输出每个字段
                console.log(`股票字段: 名称=${stockName}, 价格=${currentPrice}, 涨跌额=${changeValue}, 涨跌幅=${changePercent}, 时间=${updateTime}`);
                
                // 设置涨跌样式
                const changeClass = parseFloat(changeValue) >= 0 ? 'price-up' : 'price-down';
                
                // 设置市场状态
                let marketStatus = '已收盘';
                let statusClass = 'status-closed';
                
                if (!isTrading) {
                    marketStatus = '非交易日';
                    statusClass = 'status-non-trading';
                } else if (isMarketOpen) {
                    marketStatus = '交易中';
                    statusClass = 'status-open';
                }
                
                card.innerHTML = `
                    <div class="stock-name">
                        ${stockName}
                        <div class="market-status ${statusClass}">
                            ${marketStatus}
                        </div>
                    </div>
                    <div class="stock-code">${stockCode}</div>
                    <div class="stock-price ${changeClass}">${currentPrice}</div>
                    <div class="stock-change">
                        <span class="stock-change-value ${changeClass}">${changeValue}</span>
                        <span class="stock-change-percent ${changeClass}">${changePercent}</span>
                    </div>
                    <div class="stock-time">更新时间: ${updateTime}</div>
                    <div class="remove-btn" data-code="${stockCode}">×</div>
                `;
                
                // 添加点击事件，跳转到详情页
                card.addEventListener('click', function(e) {
                    // 如果点击的是删除按钮，不跳转
                    if (e.target.classList.contains('remove-btn')) {
                        return;
                    }
                    // 判断股票市场
                    const code = stockCode;
                    let market;
                    if (code.startsWith('60') || code.startsWith('68')) {
                        market = 'sh'; // 上海证券交易所
                    } else if (code.startsWith('00') || code.startsWith('30')) {
                        market = 'sz'; // 深圳证券交易所
                    } else {
                        market = 'bj'; // 北京证券交易所
                    }
                    const fullCode = `${market}${code}`;
                    // 跳转到腾讯财经股票详情页
                    window.open(`https://gu.qq.com/${fullCode}/zs`, '_blank');
                });
                
                // 重新绑定删除按钮的点击事件
                const removeBtn = card.querySelector('.remove-btn');
                if (removeBtn) {
                    removeBtn.addEventListener('click', async function(e) {
                        e.stopPropagation();
                        const stockCode = this.getAttribute('data-code');
                        
                        // 显示自定义确认对话框
                        showDeleteConfirmDialog(stockCode, stockName);
                    });
                }
            }
        }

        // 显示删除确认对话框
        function showDeleteConfirmDialog(stockCode, stockName) {
            // 创建模态对话框
            const modal = document.createElement('div');
            modal.className = 'delete-confirmation-modal';
            modal.style.position = 'fixed';
            modal.style.top = '0';
            modal.style.left = '0';
            modal.style.width = '100%';
            modal.style.height = '100%';
            modal.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
            modal.style.zIndex = '1000';
            modal.style.display = 'flex';
            modal.style.justifyContent = 'center';
            modal.style.alignItems = 'center';
            modal.style.animation = 'fadeIn 0.2s ease-out';
            
            // 创建模态内容
            modal.innerHTML = `
                <div class="modal-content" style="width: 320px; background: rgba(18, 18, 18, 0.95); border-radius: 10px; box-shadow: 0 0 30px rgba(138, 43, 226, 0.3); padding: 25px; animation: scaleIn 0.2s ease-out;">
                    <div class="modal-header" style="margin-bottom: 20px; text-align: center;">
                        <h2 style="margin: 0; font-size: 1.5rem; color: #e0e0e0;">删除自选股票</h2>
                    </div>
                    <div class="modal-body" style="margin-bottom: 25px; color: #e0e0e0; font-size: 1rem; line-height: 1.5; text-align: center;">
                        <div style="font-size: 3rem; margin-bottom: 15px; color: #ff6b6b;">
                            <i class="fas fa-trash-alt" style="opacity: 0.8;"></i>
                        </div>
                        <p style="margin-bottom: 5px;">确定要删除自选股票</p>
                        <p style="margin: 10px 0; font-size: 1.2rem; font-weight: bold; color: #8a2be2;">${stockCode} ${stockName || ''}</p>
                        <p style="margin-top: 5px; font-size: 0.9rem; color: #888;">删除后可重新添加</p>
                    </div>
                    <div class="modal-footer" style="display: flex; justify-content: space-between; gap: 10px;">
                        <button id="cancelDeleteBtn" style="flex: 1; padding: 12px; background: rgba(255, 255, 255, 0.1); border: 1px solid #333; border-radius: 5px; color: #e0e0e0; font-size: 1rem; cursor: pointer; transition: all 0.3s;">取消</button>
                        <button id="confirmDeleteBtn" style="flex: 1; padding: 12px; background: linear-gradient(90deg, #ff4757, #ff6b81); border: none; border-radius: 5px; color: white; font-size: 1rem; cursor: pointer; transition: all 0.3s;">删除</button>
                    </div>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(modal);
            
            // 添加CSS动画
            const style = document.createElement('style');
            style.textContent = `
                @keyframes fadeIn {
                    from { opacity: 0; }
                    to { opacity: 1; }
                }
                @keyframes scaleIn {
                    from { transform: scale(0.9); opacity: 0; }
                    to { transform: scale(1); opacity: 1; }
                }
            `;
            document.head.appendChild(style);
            
            // 添加悬停效果
            const buttons = modal.querySelectorAll('button');
            buttons.forEach(btn => {
                btn.addEventListener('mouseover', function() {
                    this.style.transform = 'translateY(-2px)';
                    if (this.id === 'confirmDeleteBtn') {
                        this.style.boxShadow = '0 5px 15px rgba(255, 71, 87, 0.4)';
                    } else {
                        this.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.3)';
                    }
                });
                
                btn.addEventListener('mouseout', function() {
                    this.style.transform = 'translateY(0)';
                    this.style.boxShadow = 'none';
                });
            });
            
            // 取消按钮点击事件
            const cancelBtn = modal.querySelector('#cancelDeleteBtn');
            cancelBtn.addEventListener('click', function() {
                document.body.removeChild(modal);
                document.head.removeChild(style);
            });
            
            // 确认删除按钮点击事件
            const confirmBtn = modal.querySelector('#confirmDeleteBtn');
            confirmBtn.addEventListener('click', async function() {
                // 禁用按钮防止重复点击
                this.disabled = true;
                this.style.opacity = '0.7';
                this.textContent = '删除中...';
                
                if (isLoggedIn) {
                    // 已登录，从服务器删除
                    try {
                        const response = await fetch('/api/remove-favorite', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ 
                                stockCode: stockCode,
                                stockName: stockName || "" // 添加stockName字段，即使为空也需要提供
                            }),
                            credentials: 'include'
                        });
                        
                        if (response.ok) {
                            // 移除对话框
                            document.body.removeChild(modal);
                            document.head.removeChild(style);
                            
                            // 重新加载自选股票
                            loadFavorites();
                        } else {
                            const errorData = await response.json();
                            alert(errorData.message || '删除自选失败，请重试');
                        }
                    } catch (error) {
                        console.error('删除自选请求错误:', error);
                        alert('网络请求失败，请检查您的网络连接');
                    }
                } else {
                    // 未登录，从本地存储删除
                    localFavorites = localFavorites.filter(item => item.code !== stockCode);
                    saveLocalFavorites();
                    renderFavorites(localFavorites);
                    
                    // 移除对话框
                    document.body.removeChild(modal);
                    document.head.removeChild(style);
                }
            });
        }

        // 返回按钮点击事件
        document.getElementById('backBtn').addEventListener('click', function() {
            if (isLoggedIn) {
                // 已登录，直接返回dashboard
                window.location.href = '/dashboard';
            } else {
                // 未登录，显示确认对话框
                if (localFavorites.length > 0) {
                    showExitConfirmDialog();
                } else {
                    // 没有自选数据，直接返回
                    window.location.href = '/blank';
                }
            }
        });
        
        // 显示退出确认对话框
        function showExitConfirmDialog() {
            console.log('显示退出确认对话框');
            
            // 先检查是否已存在对话框，如果有则移除
            const existingModal = document.querySelector('.confirmation-modal');
            if (existingModal) {
                document.body.removeChild(existingModal);
            }
            
            // 创建模态对话框
            const modal = document.createElement('div');
            modal.className = 'confirmation-modal';
            modal.style.position = 'fixed';
            modal.style.top = '0';
            modal.style.left = '0';
            modal.style.width = '100%';
            modal.style.height = '100%';
            modal.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
            modal.style.zIndex = '1000';
            modal.style.display = 'flex';
            modal.style.justifyContent = 'center';
            modal.style.alignItems = 'center';
            
            // 创建模态内容
            modal.innerHTML = `
                <div class="modal-content" style="width: 350px; background: rgba(18, 18, 18, 0.95); border-radius: 10px; box-shadow: 0 0 30px rgba(138, 43, 226, 0.3); padding: 25px;">
                    <div class="modal-header" style="margin-bottom: 20px; text-align: center;">
                        <h2 style="margin: 0; font-size: 1.8rem; background: linear-gradient(90deg, #8a2be2, #00bfff); -webkit-background-clip: text; background-clip: text; color: transparent;">确认退出</h2>
                    </div>
                    <div class="modal-body" style="margin-bottom: 25px; color: #e0e0e0; font-size: 1rem; line-height: 1.5;">
                        <p style="margin-bottom: 10px;">您当前未登录，退出后自选数据将不会保存。</p>
                        <p style="margin-bottom: 0;">您可以选择登录来保存您的自选股票。</p>
                    </div>
                    <div class="modal-footer" style="display: flex; justify-content: space-between; gap: 10px;">
                        <button id="confirmExitBtn" style="flex: 1; padding: 12px; background: linear-gradient(90deg, #ff4757, #ff6b81); border: none; border-radius: 5px; color: white; font-size: 1rem; cursor: pointer; transition: all 0.3s;">仍要退出</button>
                        <button id="confirmLoginBtn" style="flex: 1; padding: 12px; background: linear-gradient(90deg, #8a2be2, #00bfff); border: none; border-radius: 5px; color: white; font-size: 1rem; cursor: pointer; transition: all 0.3s;">我要登录</button>
                        <button id="cancelExitBtn" style="flex: 1; padding: 12px; background: rgba(255, 255, 255, 0.1); border: 1px solid #333; border-radius: 5px; color: #e0e0e0; font-size: 1rem; cursor: pointer; transition: all 0.3s;">取消</button>
                    </div>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(modal);
            
            // 添加悬停效果
            const buttons = modal.querySelectorAll('button');
            buttons.forEach(btn => {
                btn.addEventListener('mouseover', function() {
                    this.style.transform = 'translateY(-2px)';
                    if (this.id === 'confirmExitBtn') {
                        this.style.boxShadow = '0 5px 15px rgba(255, 71, 87, 0.4)';
                    } else if (this.id === 'confirmLoginBtn') {
                        this.style.boxShadow = '0 5px 15px rgba(138, 43, 226, 0.4)';
                    } else {
                        this.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.3)';
                    }
                });
                
                btn.addEventListener('mouseout', function() {
                    this.style.transform = 'translateY(0)';
                    this.style.boxShadow = 'none';
                });
            });
            
            // 直接添加事件监听器，而不是依赖id查找
            // 退出按钮点击事件
            const exitBtn = modal.querySelector('#confirmExitBtn');
            exitBtn.addEventListener('click', function() {
                console.log('退出按钮被点击');
                // 清除本地存储的自选数据
                localStorage.removeItem('favorites');
                localFavorites = [];
                // 返回blank页
                window.location.href = '/blank';
            });
            
            // 登录按钮点击事件
            const loginBtn = modal.querySelector('#confirmLoginBtn');
            loginBtn.addEventListener('click', function() {
                console.log('登录按钮被点击');
                // 临时禁用按钮防止重复点击
                this.disabled = true;
                this.style.opacity = '0.7';
                this.textContent = '正在跳转...';
                
                // 将当前页面URL存储在会话存储中，以便登录后返回
                sessionStorage.setItem('returnUrl', '/favorites');
                
                // 直接跳转，不使用setTimeout
                window.location.href = '/login';
            });
            
            // 取消按钮点击事件
            const cancelBtn = modal.querySelector('#cancelExitBtn');
            cancelBtn.addEventListener('click', function() {
                console.log('取消按钮被点击');
                // 移除模态对话框
                document.body.removeChild(modal);
            });
        }

        // 按下Alt+D显示调试信息
        document.addEventListener('keydown', function(event) {
            if (event.altKey && event.key === 'd') {
                const debugInfo = document.getElementById('debugInfo');
                debugInfo.style.display = debugInfo.style.display === 'none' ? 'block' : 'none';
                updateDebugInfo();
            }
        });

        function updateDebugInfo() {
            const output = document.getElementById('debugOutput');
            output.textContent = '页面URL: ' + window.location.href + '\n';
            output.textContent += '会话存储:\n';
            for (let i = 0; i < sessionStorage.length; i++) {
                const key = sessionStorage.key(i);
                output.textContent += `- ${key}: ${sessionStorage.getItem(key)}\n`;
            }
            output.textContent += '\n本地存储:\n';
            for (let i = 0; i < localStorage.length; i++) {
                const key = localStorage.key(i);
                output.textContent += `- ${key}: ${localStorage.getItem(key).substring(0, 50)}...\n`;
            }
        }

        function directLoginTest() {
            sessionStorage.setItem('directTestUrl', '/favorites');
            window.location.href = '/login';
        }
    </script>
    
    <!-- 版权信息 -->
    <div class="copyright-container">
        <div class="copyright">
            © 2023-2024 FinData. All Rights Reserved. 保留所有权利。
        </div>
    </div>
</body>
</html>